// pages/user/edit/edit.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
        state: null,
        region: [], // 当前地区
        infoImage: '',
        companyList:[],
        type: 1,
        isRegister: false,
        department: [[], []],
        departmentIndex: 0,
        level: [],
        levelIndex: 0,
        bg: '',
        show: true,
        otherCourtyard: '',
        showInfo: true,
        college: []
        // province: [],
        // city: [],
        // area: [],
        // mask: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.type) {
            this.setData({
                type: options.type
            })
        }
        if (options.isRegister) {
            this.setData({
                isRegister: options.isRegister
            });
        } else {
            this.setData({
              show: false
            });
            this.getUserInfo();
        }
        // 年级
        let level = [];
        for (let i = 1977; i < 2021; i++) {
            level.push(i);
        };

        this.setData({
            level: level
        });
        // 获取学院
        let _this = this;
        app.util.ajax({
            url: 'con/get_college',
            success:function(res){
                let array = [];
                for (let i = 0; i < res.data.length; i++) {
                    array.push(res.data[i].faculty);
                };
                _this.setData({
                    college: res.data,
                    'department[0]': array
                });
                _this.getFaculty(res.data[0].id);
            }
        })

        // this.setData({
        //   province: province,
        // });
        if (wx.getStorageSync('showInfo') !== '') {
          _this.setData({
            showInfo: wx.getStorageSync('showInfo')
          });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    // 分享
    onShareAppMessage(res) {
        return {
            title: '广州大学校友会校友企业家专委会',
            path: '/pages/index/index'
        }
    },
    // 获取用户信息
    getUserInfo: function() {
        let _this = this;
        app.util.ajax({
            url: 'user/business',
            data: {
                user_id: app.globalData.userInfo.user_id
            },
            success: function(res) {
                let arr = [],
                    infoData = res.info;
                if (res.info.sub) {
                    for (var i = 0, len = res.info.sub.length; i < len; i++) {
                        let obj = {};
                        obj.name = infoData.sub[i].name;
                        obj.type = infoData.sub[i].type;
                        obj.direction = infoData.sub[i].direction;
                        obj.content = infoData.sub[i].content;
                        obj.id = infoData.sub[i].id;
                        arr.push(obj);
                    }
                    let cityArr = [];
                    cityArr.push(infoData.province, infoData.city, infoData.district);
                    _this.setData({
                        companyList:arr,
                        userInfo: res.info,     
                        infoImage: res.info.images,
                        region: cityArr
                    })
                } else {
                    _this.setData({
                        userInfo: res.info,
                        infoImage: res.info.images
                    })
                };
                // 根据院系和年级渲染索引值
                for (let i = 0; i < _this.data.department.length; i++) {
                    if (_this.data.department[i] === infoData.courtyard) {
                        _this.setData({
                            departmentIndex: i
                        });
                        break;
                    };
                };
                for (let i = 0; i < _this.data.level.length; i++) {
                    if (_this.data.level[i] === infoData.grade) {
                        _this.setData({
                            levelIndex: i
                        });
                        break;
                    };
                };
            }
        })
    },
    // 上传图片
    uploadImage: function() {
        let _this = this;
        wx.chooseImage({
            count: 1,
            success: function(res) {
                wx.uploadFile({
                    url:'https://gzdx.natapp4.cc/index.php?s=/public/miniUploadImage',
                    filePath:res.tempFilePaths[0],
                    name:'file',
                    success:function(data){
                        let obj = JSON.parse(data.data);
                        _this.setData({infoImage: obj.fileName});
                    },
                    fail:function(err){
                    }
                })
            }
        })
    },
    // 选择省区
    bindRegionChange: function(e) {
        this.setData({
            region: e.detail.value
        })
    },
    // selectArea: function () {
    //   console.log(this.data.region);
    // },
    // confMask: function () {
    //   this.setData({
    //     mask: !this.data.mask
    //   });
    // },
    // selectProvice: function (e) {
    //   let provice = this.data.province[e.target.dataset.index];
    //   let region = this.data.region;
    //   this.setData({
    //     city: provice.city,
    //     region: [provice.name, '市辖区', '县级市'],
    //     area: []
    //   });
    // },
    // selectCity: function (e) {
    //   let city = this.data.city[e.target.dataset.index];
    //   let region = this.data.region;
    //   region[1] = city.name;
    //   region[2] = '县级市';
    //   this.setData({
    //     area: city.area,
    //     region: region
    //   });
    // },
    // selectArea: function (e) {
    //   let area = this.data.area[e.target.dataset.index];
    //   let region = this.data.region;
    //   region[2] = area;
    //   this.setData({
    //     region: region,
    //     region: region
    //   });
    //   this.confMask();
    // },
    // 增加公司
    addMyCompany: function() {
        let dataList = this.data.companyList,
            companyOjb = {
                name: '',
                type: '',
                direction: '',
                content: ''
            };
        dataList.push(companyOjb);
        this.setData({
            companyList: dataList
        })
    },
    // 删除公司
    deleteCompanyItem:function(e){
        let index = e.currentTarget.dataset.index,
            _this = this,
            companyList = _this.data.companyList;
        wx.showModal({
            content:'是否删除该公司',
            success:function(res){
                if (res.confirm) {
                    let companyId = companyList[index].id;
                    if (companyId) {
                      app.util.ajax({
                          url:'user/delCompany',
                          data:{
                              id:companyId
                          },
                          success:function(data){
                              wx.showToast({
                                  title:'删除公司成功'
                              })
                              companyList.splice(index,1);
                              _this.setData({
                                  companyList:companyList
                              })
                          }
                      })
                    } else {
                      companyList.splice(index, 1);
                      _this.setData({
                        companyList: companyList
                      })
                    };
                }
            }
        })
    },
    // 个人名片公司信息
    changeCompaynInput: function(e) {
        let index = e.currentTarget.dataset.index,
            type = e.currentTarget.dataset.type,
            value = e.detail.value,
            dataList = this.data.companyList;
        dataList[index][type] = value;
        this.setData({
            companyList: dataList
        })
    },
    // 提交表单
    formSubmit: function(e) {
        let _this = this,
            requestObj = {},
            formValue = e.detail.value,
            region = _this.data.region;
        for (var k in formValue) {
            if (!formValue[k]) {
                wx.showToast({
                    title: "请全部填写",
                    icon: 'none'
                })
                return
            }
        }

        if (!_this.data.infoImage) {
            wx.showToast({
                title:"请选择图片",
                icon:'none'
            })
            return;
        }
        formValue.user_id = app.globalData.userInfo ? app.globalData.userInfo.user_id : null;
        formValue.images = _this.data.infoImage;
        formValue.province = region[0];
        formValue.city = region[1];
        formValue.district = region[2];
        requestObj.info = formValue;
        requestObj.company = _this.data.companyList;
        if (!app.validate(formValue.mobile, 'phone')) {
            wx.showToast({
                title: '手机格式不正确',
                icon: 'none'
            })
            return;
        }
        if (!app.validate(formValue.empty, 'email')) {
            wx.showToast({
                title: '邮箱格式不正确',
                icon: 'none'
            })
            return;
        }
        if (_this.data.isRegister) {
            wx.login({
                success:function(res){
                    app.util.ajax({
                        url:"public/register",
                        data:{
                            code:res.code,
                            images:'',
                            nickname:''
                        },
                        success:function(data){
                            app.globalData.userInfo = data;
                            requestObj.info.user_id = data.user_id;
                            _this.submitUseForm(requestObj);
                        }
                    })
                }
            }) 
        }else{
          _this.submitUseForm(requestObj);
        }
    },
    // 提交个人名片编写表单
    submitUseForm:function(requestObj){
      let _this = this;
      if (_this.data.region[1] === '市辖区') {
        wx.showToast({
          title: '请选择市辖区',
          icon: 'none'
        });
      } else if (_this.data.region[2] === '县级市') {
        wx.showToast({
          title: '请选择县级市',
          icon: 'none'
        });
    } else {
        if (_this.data.bg === '') {
            requestObj.info.bg_image = _this.data.userInfo.bg_image;
        } else {
            requestObj.info.bg_image = _this.data.bg;
        }
        if (_this.data.userInfo.courtyard === '其他') {
          requestObj.info.courtyard = requestObj.info.otherCourtyard;
        };
        app.util.ajax({
            url: 'user/personal',
            method: 'POST',
            data: requestObj,
            success: function(res) {
                wx.showToast({
                    title: "保存信息成功",
                    icon: 'success'
                })
                _this.getUserAfreshInfo();
                setTimeout(function(){
                    _this.jumpMy();
                },2000)
            }
        })
      };
    },
    // 企业表单
    submitCompanyForm: function(e) {
        let _this = this,
            requestObj = {},
            formValue = e.detail.value,
            region = _this.data.region; 
        for (var k in formValue) {
            if (!formValue[k]) {
                wx.showToast({
                    title: "请全部填写",
                    icon: 'none'
                })
                return;
            }
        }
        if (!_this.data.infoImage) {
            wx.showToast({
                title:"请选择图片",
                icon:'none'
            })
            return;
        }
        new Promise(function(resole, reject) {
                if (!_this.data.isRegister) {
                    formValue.user_id = app.globalData.userInfo.user_id;
                    resole();
                } else {
                    wx.login({
                        success: function(res) {
                            formValue.code = res.code;
                            resole();
                        }
                    })
                }
            })
            .then((res) => {
                // formValue.images = _this.data.infoImage;
                formValue.uploadImage = _this.data.infoImage;
                formValue.province = region[0];
                formValue.city = region[1];
                formValue.district = region[2]; 
                let url = '';
                if (_this.data.isRegister) {
                    url = 'public/registerEnterprise';
                    // formValue.uploadImage = _this.data.infoImage;
                }else{
                    url = 'user/enterprise';
                    // formValue.images = _this.data.infoImage;
                }
                app.util.ajax({
                    url: url,
                    data: formValue,
                    success: function(res) {
                        let tipsMsg = _this.data.isRegister ? '企业注册成功' : '修改保存成功';
                        wx.showToast({
                            title:tipsMsg
                        });
                        if (!_this.data.isRegister) {
                            _this.getUserAfreshInfo();
                        }
                        setTimeout(function(){
                            _this.jumpMy();
                        },2000)
                    }
                })
            })
            .catch(err => {
                wx.showToast({
                    title: '注册失败',
                    icon: 'none'
                })
            })
    },
    // 跳转页面
    jumpMy:function(){
        wx.switchTab({
            url:'/pages/user/user'
        })
    },
    // 重新获取用户最新信息
    getUserAfreshInfo:function(){
        let _this = this;
        app.util.ajax({
            url:'user/getMember',
            data:{
                id:app.globalData.userInfo.user_id
            },
            success:function(res){
                let info = res.member;
                info.user_id = res.member.member_id;
                app.globalData.userInfo = info;
                wx.setStorageSync('userInfo',info);
            }
        })
    },
    // 选择改变院系
    departmentChange: function (e) {
        if (e.detail.value[1] === null) {
            e.detail.value[1] = 0;
        };
        this.setData({
            'userInfo.courtyard': this.data.department[0][e.detail.value[0]] + this.data.department[1][e.detail.value[1]],
            // departmentIndex: e.detail.value
        });
    },
    departmentChange2: function (e) {
        if (e.detail.column === 0) {
            this.getFaculty(this.data.college[e.detail.value].id);
        };
    },
    // 选择改变年级
    levelChange: function (e) {
        this.setData({
            'userInfo.grade': this.data.level[e.detail.value],
            levelIndex: e.detail.value
        });
    },
  changeBg: function () {
    let _this = this;
    wx.showModal({
      title: '更换名片封面',
      success(res) {
        if (res.confirm) {
          wx.chooseImage({
            count: 1,
            success: function (res) {
              wx.uploadFile({
                url: 'https://gzdx.natapp4.cc/index.php?s=/public/miniUploadImage',
                filePath: res.tempFilePaths[0],
                name: 'file',
                success: function (data) {
                  let obj = JSON.parse(data.data);
                  _this.setData({
                    bg: obj.fileName,
                    'userInfo.bg_image': obj.fileName
                  });
                },
                fail: function (err) {
                }
              })
            }
          })  
        }
      }
    })
  },
  // 获取微信信息
  getWxInfo () {
    let _this = this;
    wx.getUserInfo({
      success: (res) => {
        _this.setData({
          // 'userInfo.nickname': res.userInfo.nickname,
          infoImage: res.userInfo.avatarUrl
        })
      },
      complete: (res) => {
        _this.setData({
          show: false
        });
      }
    })
  },
  // 控制信息显示隐藏
  confirmInfo () {
    this.setData({
      showInfo: !this.data.showInfo
    });
    wx.setStorageSync('showInfo', this.data.showInfo);
  },
//   获取系
  getFaculty (id) {
    let _this = this;
    app.util.ajax({
        url: 'con/get_faculty',
        data: {
            id: id
        },
        success:function(res){
            let array = [];
            for (let i = 0; i < res.data.length; i++) {
                array.push(res.data[i].faculty);
            };
            _this.setData({
                'department[1]': array
            });
        }
    })
  }
})